package com.qimo.zuoyeoa.controller;


import com.github.pagehelper.PageInfo;
import com.qimo.zuoyeoa.entity.JobLogin;
import com.qimo.zuoyeoa.entity.Schedule;
import com.qimo.zuoyeoa.entity.User;
import com.qimo.zuoyeoa.service.ScheduleService;
import com.qimo.zuoyeoa.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ScheduleController {
    private static final Logger logger = LoggerFactory.getLogger(ScheduleController.class);

    // 使用@Autowired注解标注的成员变量，可以有Spring框架自动为这个变量赋值
    // 所同值是@Service标注的该接口类型的实现类对象实例。
    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private UserService userService;

    @GetMapping("/schedule/schedule_add")
    public ModelAndView scheduleAddView(){
        ModelAndView mav = new ModelAndView("schedule/schedule_add");
        List<User> users = userService.findAll();
        mav.addObject("users",users);
        return mav;
    }

    @GetMapping("/schedule/schedule_list")
    public ModelAndView scheduleListView(
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize",required = true,defaultValue = "5") int pageSize,
            @RequestParam(name = "keyword", required = false) String keyword
    ){
        ModelAndView mav = new ModelAndView("schedule/schedule_list");
        // 调用服务方法查询分页的客户数据
        PageInfo<Schedule> page = scheduleService.findByKeyword(pageNum,pageSize,keyword);
//        System.out.println(page);
        mav.addObject("page",page);
        return mav;
    }

    @GetMapping("/schedule/schedule_modify")
    public ModelAndView scheduleModifyView(
            @RequestParam(name = "id", required = true) int id,
            @RequestParam(name = "pageSize",required = true,defaultValue = "5") int pageSize,
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "keyword", required = false) String keyword
    ){
        ModelAndView mav = new ModelAndView("schedule/schedule_modify");
        List<User> users = userService.findAll();
        mav.addObject("users",users);
        // 调用服务方法根据ID查询编辑客户
        Schedule schedule = scheduleService.findById(id);
        mav.addObject("schedule",schedule);
        return mav;
    }

    @PostMapping("/schedule/schedule_add")
    // @Validated注解所标注的参数，表明该参数中的属性取值必须要按照属性上定义的验证规则进行验证，验证是由框架完成的。
    // 验证的结果会以BindingResult实例的形式传入到该方法中
    public ModelAndView scheduleAdd(@Validated Schedule schedule, BindingResult bindingResult){

        // redirect表示重定向响应
        // 给浏览器发送一个请求地址，而没有任何试图内容或数据。
        // 浏览器会使用收到的地址，重新发送一个Get请求。由于是新请求，因此没有缓存上一次请求的数据，从而达到防止重复提交表单的目的
        ModelAndView mav = new ModelAndView("redirect:/schedule/schedule_add");
        Map<String, String> errorMessages = new HashMap<>();
        if (bindingResult.hasErrors()){
            // 如果有验证错误信息，那么要进行处理

            final List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            // 错误信息放入到映射中
            for (FieldError error : fieldErrors) {
                // 从每一个域错误对象中取出域名称
                errorMessages.put(error.getField(), error.getDefaultMessage());
            }
            //
            mav.addObject("errorMessages",errorMessages);
            //
            mav.addObject("schedule",schedule);
            //
            mav.setViewName("schedule/schedule_add");
        }else {
            // 如果没有错误信息，验证通过，保存客户信息
            // 调用服务方法保存客户数据
            boolean result = scheduleService.append(schedule);
            if (result) {
                logger.info("新增客户信息成功 - " + schedule);
            }else {
                logger.info("新增客户信息失败 - " + schedule);
            }
        }
        return mav;
    }

    @PostMapping("/schedule/schedule_modify")
    public ModelAndView scheduleModify(
            Schedule schedule,
            @RequestParam(name = "pageNum", required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", required = true,defaultValue = "5") int pageSize,
            @RequestParam(name = "keyword", required = false) String keyword
    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/schedule/schedule_list?pageNum=" + pageNum + "&pageSize=" + pageSize +"&keyword=" + URLEncoder.encode(keyword,"utf-8");
        ModelAndView mav = new ModelAndView(redirectUrl);
        boolean result = scheduleService.modify(schedule);
        return mav;
    }

    @GetMapping("/schedule/schedule_remove")
    public ModelAndView scheduleRemove(
            @RequestParam(name = "id", required = true) int id,
            @RequestParam(name = "pageSize",required = true,defaultValue = "5") int pageSize,
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "keyword", required = false) String keyword
    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/schedule/schedule_list?pageNum=" + pageNum + "&pageSize=" + pageSize +"&keyword=" + URLEncoder.encode(keyword,"utf-8");
        ModelAndView mav = new ModelAndView(redirectUrl);
        // 调用服务方法根据ID查询编辑客户
        boolean result = scheduleService.remove(id);
        return mav;
    }

    @GetMapping("/schedule/schedule_detail")
    public ModelAndView productDetail(@RequestParam(name = "id", required = true) int id){
        ModelAndView mav = new ModelAndView("schedule/schedule_detail");
        Schedule schedule = scheduleService.findById(id);
        List<User> users = userService.findAll();
        mav.addObject("users",users);
        mav.addObject("schedule",schedule);
        return mav;
    }
}
